//
//  main.swift
//  Auto114Tool
//
//  Created by yangbin on 2020/8/25.
//  Copyright © 2020 RMCtl. All rights reserved.
//

import Foundation



print("Choose start model: \n 1. immediately start   2. auto start   3. config")
let inputs = readLine() ?? "1"
if inputs == "1" {
    start()
} else if inputs == "2" {
    print("input start time : (yyyy-MM-dd HH:mm)")
    while let time = readLine() {
        autoStart(str: time)
        break
    }
} else if inputs == "3" {
    let worker = Worker()
    func getValue(kp: ReferenceWritableKeyPath<Worker, String>, name: String) {
        print("\(name): (\(worker[keyPath: kp]))")
        let input = readLine() ?? ""
        worker[keyPath: kp] = input.isEmpty ? worker[keyPath: kp] : input
    }
    
    getValue(kp: \.hospitalCode, name: "hospitalCode")
    getValue(kp: \.firstDeptCode, name: "firstDeptCode")
    getValue(kp: \.secondDeptCode, name: "secondDeptCode")
    getValue(kp: \.doctorName, name: "doctorName")
    getValue(kp: \.targetDate, name: "targetDate")
    getValue(kp: \.cardType, name: "cardType")
    getValue(kp: \.cardNumber, name: "cardNumber")
    getValue(kp: \.phoneNumber, name: "phoneNumber")
    getValue(kp: \.name, name: "name")

    print("input start time : (yyyy-MM-dd HH:mm)")
    while let time = readLine() {
        autoStart(str: time, worker: worker)
        break
    }
    
}
else {
    exit(1)
}

RunLoop.current.run()

func autoStart(str: String, worker: Worker? = nil) {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm"
    let date = formatter.date(from: str) ?? Date()
    LogViewUtility.log("auto start at: \(date)")
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in
        let interval = date.timeIntervalSinceNow
        if interval < 4.5 {
            LogViewUtility.log("auto start now!")
            start(worker: worker)
            t.invalidate()
        } else {
            LogViewUtility.log("auto will start after \(Int(interval))s")
        }
    }
}
func start(worker: Worker? = nil) {
    let worker1 = worker ?? Worker()
    worker1.work()
}
